<template>
  <a-spin :spinning="spinning" tip="加载中...">
    <a-card :bordered="false">
      <h3 style="margin-bottom: 20px;">{{ id == 'null' ? '新增' : '编辑' }}话题</h3>
      <h4 class="title">话题编辑</h4>
      <a-form-model ref="rulesForm" :model="form" :rules="rules" :labelCol="{ lg: { span: 4 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
        <a-form-model-item label="话题类型" prop="topicType">
          <a-radio-group v-model="form.topicType" :disabled="id != 'null'">
            <a-radio :value="0">普通话题</a-radio>
            <a-radio :value="1">有奖话题</a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="话题名称" prop="topicName">
          <a-input v-model="form.topicName" :maxLength="topicNameLimit" placeholder="话题名称不用填#" allowClear :suffix="`${topicNameNumber}/${topicNameLimit}`" />
        </a-form-model-item>
        <a-form-model-item label="话题简介" prop="topicIntroduction">
          <a-textarea v-model="form.topicIntroduction" :maxLength="topicIntroductionLimit" placeholder="" :rows="4" allowClear />
          <div class="limit-text">{{ `${topicIntroductionNumber}/${topicIntroductionLimit}` }}</div>
        </a-form-model-item>
        <a-form-model-item label="话题活动时间" prop="time">
          <a-range-picker style="width:100%;" show-time valueFormat="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" v-model="form.time" />
        </a-form-model-item>
        <a-form-model-item label="话题图片" required>
          <JImageUpload
            :uploadParams="getUploadParams()"
            :isMove="false"
            :isMultiple="true"
            :fileSize="10"
            :number="1"
            :accept="'image/*'"
            @fileChange="fileImageChange"
            v-model="topicImageList"
          ></JImageUpload>
          <div>270*270px，支持jpg、png、gif图片格式</div>
        </a-form-model-item>
        <a-form-model-item label="话题页背景图" required>
          <JImageUpload
            :uploadParams="getUploadParams()"
            :isMove="false"
            :isMultiple="true"
            :fileSize="10"
            :number="1"
            :accept="'image/*'"
            @fileChange="fileBehindImageChange"
            v-model="behindImageList"
          ></JImageUpload>
          <div>1125*774px，支持jpg、png、gif图片格式</div>
        </a-form-model-item>
        <a-form-model-item label="话题指定商品">
          <a-table bordered :pagination="false" :columns="productColumns" :data-source="form.communityTopicAssGoodsDtoList" :rowKey="(record, index) => index">
            <span class="product" slot="product" slot-scope="text, record, index">
              <img class="img" :src="record.image" alt="" />
              <div style="margin-left: 10px;flex: 1;display: flex;align-items: center;">
                <div class="product-name">【{{ record.brandName }}】{{ record.productName }}</div>
              </div>
            </span>
            <span slot="action" slot-scope="text, record, index">
              <a :disabled="productFlag" @click="handleRemoveProduct(index)">删除</a>
            </span>
          </a-table>
          <a @click="productVisible = true" v-if="form.communityTopicAssGoodsDtoList.length < 10">添加关联商品</a>
        </a-form-model-item>
        <a-form-model-item v-if="form.topicType == 0" label="话题适用小程序" prop="checkboxTopicProgramId">
          <a-checkbox-group v-model="form.checkboxTopicProgramId">
            <a-checkbox :value="item.weid" v-for="item in brandList" :key="item.weid"> {{ item.name }}微商城 </a-checkbox>
          </a-checkbox-group>
        </a-form-model-item>
        <a-form-model-item v-if="form.topicType == 1" label="话题适用小程序" prop="selectTopicProgramId">
          <a-select v-model="form.selectTopicProgramId" placeholder="请选择" show-search :filter-option="filterOption">
            <a-select-option :value="item.weid" v-for="item in brandList" :key="item.weid"> {{ item.name }}微商城 </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="用户端话题数据" prop="dataType">
          <a-radio-group v-model="form.dataType">
            <a-radio :value="0">隐藏</a-radio>
            <a-radio :value="1">展示</a-radio>
          </a-radio-group>
          <a @click="isShowExample=!isShowExample">用户端话题数据示意图 ></a>
          <img width="240" v-if="isShowExample" style="vertical-align: top;margin-left: 10px;" src="https://picttype1.jnby.com/zhongtai/lQLPJxZ9ALzt2VPNAwjNBGWwOBDYwvx7508Czd76rMAzAA_1125_776.png" alt="" />
        </a-form-model-item>
        <template v-if="form.topicType == 1">
          <h4 class="title">奖励设置</h4>
          <a-form-model-item label="获奖方式" prop="rewardWay">
            <a-radio-group v-model="form.rewardWay">
              <a-radio :value="0">按点赞数排名获奖</a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="奖品设置" required>
            <a-table bordered :scroll="{ x: true }" :pagination="false" :columns="prizeColumns" :data-source="form.communityRewardDtoList" :rowKey="(record, index) => index">
              <span slot="userNumber" slot-scope="text, record, index">
                <a-form-model-item label="" :prop="`communityRewardDtoList.${index}.userNumber`" :rules="rules.userNumber">
                  <a-input-number style="width: 100%;" v-model.trim="record.userNumber" :min="0" placeholder="" />
                </a-form-model-item>
              </span>
              <span slot="rewardType" slot-scope="text, record, index">
                <a-form-model-item label="" :prop="`communityRewardDtoList.${index}.rewardType`" :rules="rules.rewardType">
                  <a-select v-model="record.rewardType" style="width: 100%;" show-search :filter-option="filterOption">
                    <a-select-option :value="0">
                      优惠券
                    </a-select-option>
                    <a-select-option :value="1">
                      实物
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </span>
              <span slot="rewardName" slot-scope="text, record, index">
                <a-form-model-item label="" :prop="`communityRewardDtoList.${index}.rewardName`" :rules="rules.rewardName">
                  <a-input style="width: 100%;" v-model.trim="record.rewardName" placeholder="" allowClear />
                </a-form-model-item>
              </span>
              <span slot="rewardPrice" slot-scope="text, record, index">
                <a-form-model-item label="" :prop="`communityRewardDtoList.${index}.rewardPrice`" :rules="rules.rewardPrice">
                  <a-input style="width: 100%;" v-model.trim="record.rewardPrice" placeholder="" allowClear />
                </a-form-model-item>
              </span>
              <span slot="rewardContact" slot-scope="text, record, index">
                <a-form-model-item label="" :prop="`communityRewardDtoList.${index}.rewardContact`" :rules="rules.rewardContact">
                  <a-input style="width: 100%;" v-model.trim="record.rewardContact" placeholder="" allowClear />
                </a-form-model-item>
              </span>
              <span class="prize-img" slot="rewardImage" slot-scope="text, record, index">
                <a-form-model-item label="" :prop="`communityRewardDtoList.${index}.rewardImage`" :rules="rules.rewardImage">
                  <JImageUpload
                    :isMove="false"
                    :uploadParams="getUploadParams()"
                    :isMultiple="true"
                    :fileSize="10"
                    :number="1"
                    :accept="'image/*'"
                    @fileChange="fileRewardImageChange(arguments, index)"
                    v-model="rewardImageList[index]"
                  ></JImageUpload>
                </a-form-model-item>
              </span>
              <span slot="action" slot-scope="text, record, index">
                <a :disabled="rewardFlag" @click="handleRemovePrize(index)">删除</a>
              </span>
            </a-table>
            <div style="display: flex;justify-content: space-between;">
              <a @click="handleAddPrize">添加奖励</a>
              <div>奖品图尺寸240*240px，支持jpg、png、gif图片格式</div>
            </div>
          </a-form-model-item>
          <a-form-model-item label="奖励规则" prop="rewardRules">
            <a-textarea v-model="form.rewardRules" :maxLength="rewardRulesLimit" placeholder="填写话题奖励规则" :rows="4" allowClear />
            <div class="limit-text">{{ `${rewardRulesNumber}/${rewardRulesLimit}` }}</div>
          </a-form-model-item>
        </template>
        <h4 class="title">分享设置 <span>未定义该设置，将默认取话题背景图和话题名称做分享标题和图片</span></h4>
        <a-form-model-item class="share-img" label="小程序分享卡片图">
          <JImageUpload
            :isMove="false"
            :uploadParams="getUploadParams()"
            :isMultiple="true"
            :fileSize="10"
            :number="1"
            :accept="'image/*'"
            @fileChange="fileShareImageChange"
            v-model="shareImageList"
          ></JImageUpload>
          <div style="margin-top: -15px;">500*400px</div>
        </a-form-model-item>
        <a-form-model-item label="小程序分享标题">
          <a-textarea v-model="form.shareTitle" :maxLength="36" placeholder="小程序分享卡片展示的标题文案，最多36个字" :rows="3" allowClear />
        </a-form-model-item>
        <a-form-model-item :wrapperCol="{ span: 24 }" style="text-align: center">
          <a-button style="margin-right: 8px" @click="handleBack">取消</a-button>
          <a-button htmlType="submit" @click="handleSubmit" type="primary">发布</a-button>
        </a-form-model-item>
      </a-form-model>
      <a-modal title="添加关联商品" :visible="productVisible" width="500px" @ok="handleProductSubmit" @cancel="productVisible = false">
        <a-form-model ref="productForm" :model="productForm" :rules="productRules">
          <a-form-model-item prop="productNo">
            <a-input v-model.trim="productForm.productNo" placeholder="请输入商品SPU" allowClear />
          </a-form-model-item>
        </a-form-model>
        <div>* 请保证添加的商品在伯俊已完善SPU信息，否则，将无法添加成功</div>
      </a-modal>
    </a-card>
  </a-spin>
</template>
<script>
import JImageUpload from '../../components/JImageUpload'
import { brandList } from '../../components/brandList.js'
import { topicAddOrUpdate, querySpu, topicDetails, topicDelAssGoods,topicDelReward } from '@/api/micromall/communityContent'
const productColumns = [
  {
    title: '序号',
    width: '50px',
    align: 'center',
    customRender: (text, record, index) => `${index + 1}`
  },
  {
    title: '商品',
    width: '200px',
    scopedSlots: { customRender: 'product' }
  },
  {
    title: '款号',
    width: '120px',
    align: 'center',
    dataIndex: 'productNo'
  },
  {
    title: '操作',
    width: '120px',
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]

const prizeColumns = [
  {
    title: '奖励序号',
    width: '100px',
    align: 'center',
    customRender: (text, record, index) => `${index + 1}等奖`
  },
  {
    title: '中奖人数',
    width: '100px',
    align: 'center',
    scopedSlots: { customRender: 'userNumber' }
  },
  {
    title: '奖励类型',
    width: '120px',
    align: 'center',
    scopedSlots: { customRender: 'rewardType' }
  },
  {
    title: '奖品名称',
    width: '150px',
    align: 'center',
    scopedSlots: { customRender: 'rewardName' }
  },
  {
    title: '奖品价值(元)',
    width: '120px',
    align: 'center',
    scopedSlots: { customRender: 'rewardPrice' }
  },
  {
    title: '奖品关联ID',
    width: '150px',
    align: 'center',
    scopedSlots: { customRender: 'rewardContact' }
  },
  {
    title: '奖品图',
    width: '100px',
    align: 'center',
    scopedSlots: { customRender: 'rewardImage' }
  },
  {
    title: '操作',
    width: '80px',
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  components: {
    JImageUpload
  },
  data() {
    return {
      isShowExample: false,
      productFlag: false,
      rewardFlag: false,
      id: this.$route.params.id,
      productColumns,
      brandList,
      topicImageList: [],
      behindImageList: [],
      shareImageList: [],
      rewardImageList: [],
      prizeColumns,
      productForm: {},
      productRules: {
        productNo: [{ required: true, message: '请输入', trigger: 'blur' }]
      },
      productVisible: false,
      topicNameLimit: 10,
      topicNameNumber: 0,
      topicIntroductionLimit: 40,
      topicIntroductionNumber: 0,
      rewardRulesLimit: 300,
      rewardRulesNumber: 0,
      spinning: false,
      form: {
        rewardWay: 0,
        topicName: '',
        topicIntroduction: '',
        rewardRules: '',
        communityRewardDtoList: [
          {
            userNumber: '',
            rewardType: '',
            rewardName: '',
            rewardPrice: '',
            rewardContact: '',
            rewardImage: []
          }
        ],
        dataType: 0,
        topicType: 0,
        communityTopicAssGoodsDtoList: []
      },
      rules: {
        topicName: [{ required: true, message: '请输入', trigger: 'blur' }],
        topicType: [{ required: true, message: '请选择', trigger: 'change' }],
        topicIntroduction: [{ required: true, message: '请选择', trigger: 'change' }],
        checkboxTopicProgramId: [{ required: true, message: '请选择', trigger: 'change' }],
        selectTopicProgramId: [{ required: true, message: '请选择', trigger: 'change' }],
        dataType: [{ required: true, message: '请选择', trigger: 'change' }],
        time: [{ required: true, message: '请选择', trigger: 'change' }],
        rewardImage: [{ required: true, message: '请上传' }],
        userNumber: [{ required: true, message: '请输入', trigger: 'blur' }],
        rewardType: [{ required: true, message: '请选择', trigger: 'change' }],
        rewardName: [{ required: true, message: '请输入', trigger: 'blur' }],
        rewardPrice: [
          { required: true, message: '请输入', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              const reg = /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/
              if (!value && value !== 0) {
                callback()
              } else {
                if (reg.test(value)) {
                  callback()
                } else {
                  return callback(new Error('请输入正确的金额'))
                }
              }
            },
            trigger: 'blur'
          }
        ],
        rewardContact: [{ required: true, message: '请输入', trigger: 'blur' }],
        rewardWay: [{ required: true, message: '请选择', trigger: 'change' }],
        rewardRules: [{ required: true, message: '请输入', trigger: 'blur' }]
      }
    }
  },
  watch: {
    form: {
      handler: function() {
        const _this = this
        _this.topicNameNumber = _this.form.topicName.length
        _this.topicIntroductionNumber = _this.form.topicIntroduction.length
        _this.rewardRulesNumber = _this.form.rewardRules.length
      },
      deep: true
    }
  },
  created() {
    this.getDetails()
  },
  computed: {},
  mounted() {},
  methods: {
    // 删除奖励
    handleRemovePrize(index) {
      this.form.communityRewardDtoList.splice(index, 1)
    },

    // 添加奖励
    handleAddPrize() {
      if (this.form.communityRewardDtoList.length >= 10) {
        this.$message.info('奖品设置已上限！')
        return
      }
      this.form.communityRewardDtoList.push({
        userNumber: '',
        rewardType: '',
        rewardName: '',
        rewardPrice: '',
        rewardContact: '',
        rewardImage: []
      })
    },

    // 关联商品
    handleProductSubmit() {
      this.$refs.productForm.validate(valid => {
        if (valid) {
          const data = {
            ...this.productForm
          }
          const filterList = this.form.communityTopicAssGoodsDtoList.filter(e => e.productNo == this.productForm.productNo)
          if (filterList.length) {
            this.$message.info('该商品已存在！')
            return
          }
          this.productVisible = false
          querySpu(data).then(res => {
            if (res.code === 200) {
              this.productForm = {}
              const item = {
                  ...res.data,
                  id: null
                }
              this.form.communityTopicAssGoodsDtoList.push(item)
            } else {
              // this.$message.info('添加的商品未在伯俊完善SKU信息，添加失败！')
              this.$message.error(res.msg || res.message)
            }
          })
          // 添加成功
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    // 获取详情
    getDetails() {
      if (this.id == 'null') return
      const data = {
        id: this.id
      }
      topicDetails(data)
        .then(res => {
          if (res.code === 200) {
            const { topicType, topicImage, behindImage, shareImage, communityRewardDtoList, startTime, endTime, topicProgramId } = res.data
            this.form = {
              ...res.data,
              time: [startTime, endTime],
              checkboxTopicProgramId: (topicType == '0' && topicProgramId) ? topicProgramId.split(',') : [],
              selectTopicProgramId: topicType == '1' ? topicProgramId : '',
              rewardRules: (topicType == '1' && communityRewardDtoList.length) ? communityRewardDtoList[0].rewardRules : '',
              rewardWay: (topicType == '1' && communityRewardDtoList.length) ? communityRewardDtoList[0].rewardWay : ''
            }
            this.topicImageList = topicImage ? topicImage.split(',') : []
            this.behindImageList = behindImage ? behindImage.split(',') : []
            this.shareImageList = shareImage ? shareImage.split(',') : []
            this.rewardImageList = (topicType == '1' && communityRewardDtoList.length) ? communityRewardDtoList.map(e => e.rewardImage) : []
          } else {
            this.$message.error(res.data.msg)
          }
        })
        .catch(err => {})
    },

    // 移除关联商品
    handleRemoveProduct(index) {
     this.form.communityTopicAssGoodsDtoList.splice(index, 1)
    },

    getUploadParams() {
      return {
        actionUrl: 'https://jic.jnby.com/activity/market-act/common/upload/multipart',
        headers: {
          authorization: 'authorization-text'
        },
        uploadHost: 'https://img.bzhz.jnbygroup.com/'
      }
    },

    // 图片change
    fileImageChange(list) {
      this.form.topicImage = list.length ? list[0].url : ''
    },

    // 背景图
    fileBehindImageChange(list) {
      this.form.behindImage = list.length ? list[0].url : ''
    },

    // 分享图
    fileShareImageChange(list) {
      this.form.shareImage = list.length ? list[0].url : ''
    },

    fileRewardImageChange(list, index) {
      this.form.communityRewardDtoList[index].rewardImage = list.length ? list[0] : []
      this.$refs.rulesForm.validate()
    },

    // 确认同步
    handleSubmit() {
      this.$refs.rulesForm.validate(valid => {
        if (valid) {
          const { topicType, checkboxTopicProgramId, selectTopicProgramId, time, communityRewardDtoList, topicImage, behindImage, rewardRules, rewardWay } = this.form
          if (!topicImage) {
            this.$message.error('无话题图片！')
            return
          }
          if (!behindImage) {
            this.$message.error('无话题页背景图片！')
            return
          }
          if (!communityRewardDtoList.length && topicType == '1') {
            this.$message.error('无奖品设置！')
            return
          }
          let currentCommunityRewardDtoList
          let checkboxTopicProgram = []
          let selectTopicProgram
          if (topicType == '1') {
            currentCommunityRewardDtoList = communityRewardDtoList.map((e, index) => {
              return {
                ...e,
                rewardImage: e.rewardImage[0].url,
                rewardRules,
                rewardWay,
                serialNumber: index + 1
              }
            })

            selectTopicProgram = this.brandList.filter(e => e.weid == selectTopicProgramId).map(i => i.name + '微商城')[0]
          } else {
            checkboxTopicProgramId.forEach(e => {
              checkboxTopicProgram = checkboxTopicProgram.concat(this.brandList.filter(i => i.weid == e).map(i => i.name + '微商城'))
            })
          }
          const data = {
            ...this.form,
            startTime: time[0],
            endTime: time[1],
            topicProgramId: topicType == '0' ? checkboxTopicProgramId.join(',') : selectTopicProgramId,
            topicProgram: topicType == '0' ? checkboxTopicProgram.join(',') : selectTopicProgram,
            communityRewardDtoList: topicType == '1' ? currentCommunityRewardDtoList : null
          }
          this.spinning = true
          topicAddOrUpdate(data)
            .then(res => {
              if (res.code === 200) {
                this.$router.go(-1)
              } else {
                this.spinning = false
                this.$message.error(res.msg)
              }
            })
            .catch(err => {
              this.spinning = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    //返回
    handleBack() {
      this.$router.go(-1)
    },

    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    }
  }
}
</script>
<style lang="less" scoped>
.limit-text {
  position: absolute;
  left: 0;
  bottom: 0;
  right: 10px;
  text-align: right;
}
/deep/.ant-checkbox-wrapper {
  margin-left: 0;
  margin-right: 8px;
}
.ant-spin-nested-loading /deep/ .ant-spin {
  top: 50%;
  transform: translateY(-50%);
}
/deep/.ant-tag {
  cursor: pointer;
}
.title {
  font-size: 15px;
  span {
    color: #999;
    font-size: 14px;
    font-weight: normal;
  }
}
.product {
  .img {
    display: block;
    margin: 0 2px;
    width: 60px;
    height: 60px;
    border: 1px dashed #f5f5f5;
    object-fit: scale-down;
    cursor: pointer;
  }
}

.remarks {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  word-break: break-all; /* 追加这一行代码 */
  /* autoprefixer: off */
  -webkit-box-orient: vertical;
  /* autoprefixer: on */
}
.product {
  display: flex;
  overflow: hidden;
  .img {
    margin: 0;
  }
  .product-name {
    flex: 1;
    margin-left: 5px;
    text-align: left;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    word-break: break-all; /* 追加这一行代码 */
    /* autoprefixer: off */
    -webkit-box-orient: vertical;
    /* autoprefixer: on */
  }
}
.share-img /deep/ .ant-upload-list-picture-card .ant-upload-list-item {
  height: 80px;
}
.share-img /deep/ .ant-upload.ant-upload-select-picture-card {
  height: 80px;
}
.share-img /deep/ .ant-upload-list-picture-card-container {
  height: 80px;
}
.prize-img /deep/ .ant-upload-list-picture-card .ant-upload-list-item {
  margin: 0 auto;
  width: 90px;
  height: 90px;
}
.prize-img /deep/ .ant-upload.ant-upload-select-picture-card {
  margin: 0 auto;
  float: none;
  width: 90px;
  height: 90px;
}
.prize-img /deep/ .my-img-item {
  margin: 0 auto;
  width: 90px;
  height: 90px;
}
.prize-img /deep/ .my-img-list-wrapper {
  margin: 0 auto;
  width: 90px;
}
/deep/ .my-img-item {
  margin: 0 8px 8px 0;
}
</style>
